package com.hjm.project.settleInfo.settleInfo.utils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hjm.common.utils.LogUtils;
import com.hjm.common.utils.request.AutoLoadData;
import com.hjm.common.utils.request.HttpClientUtils;
import com.hjm.common.utils.trade.DateUtil;
import com.hjm.common.utils.trade.LoFunction;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import static com.hjm.common.utils.DigestUtils.encodeShaHexStr;

/**
 * @ClassName ComeMoney
 * @Deacription 出款接口信息
 * @Version 1.0
 **/
public class ComeMoney {

    private static Socket socket;
    private static OutputStream os;
    private static InputStream is;

    public static final String zz_url="http://localhost:8080/qb-pro/agent/addAgentMoney.do";
    public static final String tx_url="http://localhost:8080/qb-pro/agent/agentReflect.do";

    //    public static final String zz_url="http://localhost:8080/qck_pro/agent/addAgentMoney.do";
//    public static final String tx_url="http://localhost:8080/qck_pro/agent/agentReflect.do";
    public static final String qry_url="http://localhost:8080/qb_pro/agent/getOrderInfoBySerial.do";


    public static final String NEW_OUT = "http://192.168.1.40:8080/qck-pro/agent/orderByNewOut.do";



    /**
     *
     * @Param [settleSerial 出款流水]
     * @Return void
     */
    public static String query(String settleSerial) {
        LogUtils.logInfo("开始进行查询:" + settleSerial);
        try {
           Map map = new HashMap();
            map.put("settleSerial", settleSerial);
            map.put("sign", encodeShaHexStr(map));
            Map hasMap = new HashMap();
            //加密值
            String data = JSONObject.toJSONString(map);
            hasMap.put("data", AESUtil.encrypt(data, "98219030384df694a1db622d0541047c"));
            LogUtils.logInfo("未知查询报文签名:" + hasMap);
            JSONObject resultBody = HttpClientUtils.sendHttpPostForm(qry_url, hasMap);
            LogUtils.logInfo("未知查询响应结果:" + resultBody.toString());
            return resultBody.toString();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logInfo("未知查询异常:" + e);
        }
        return null;
    }

    /**
     * 重新出款接口
     * @Param [settleSerial]
     * @Return java.lang.String
     */
    public static Map<String,String> newOut(String settleSerial) {
        Map<String, String> result = Maps.newHashMap();
        try {
            LogUtils.logInfo("开始进行出款:" + settleSerial);
            Map map = new HashMap();
            map.put("settleSerial", settleSerial);
            map.put("sign", encodeShaHexStr(map));
            Map hasMap = new HashMap();
            //加密值
            String data = JSONObject.toJSONString(map);
            hasMap.put("data", AESUtil.encrypt(data, "98219030384df694a1db622d0541047c"));
            LogUtils.logInfo("重新出款报文签名:" + hasMap);
            JSONObject resultBody = HttpClientUtils.sendHttpPostForm(AutoLoadData.restartCome, hasMap);
            LogUtils.logInfo("重新出款响应结果:" + resultBody.toString());
            String outerLayer = resultBody.getString("responseVal");
            String code = resultBody.getString("responseCode");
            if ("200".equals(code)) {
                Map maps = (Map) JSON.parse(outerLayer);
                String innerLayer = AESUtil.decrypt(maps.get("data").toString(), "98219030384df694a1db622d0541047c");
                Map tomap = (Map) JSON.parse(innerLayer);
                LogUtils.logInfo("解密响应报文:" + tomap);
                if ("200".equals(tomap.get("code") + "")) {
                    String sign = tomap.get("sign").toString();
                    tomap.remove("sign");
                    tomap.remove("msg");
                    tomap.remove("code");
                    if (StringUtils.isEmpty(sign) || !encodeShaHexStr(tomap).equals(sign)) {
                         LogUtils.logInfo("签名错误:" + settleSerial);
                        result.put("code","300");
                        result.put("msg","签名验证失败");
                        return result;

                    } else {
                        LogUtils.logInfo("操作成功:" + settleSerial);
                        result.put("code","200");
                        result.put("msg","操作成功" + tomap.get("msg"));
                        return result;
                    }
                } else {
                    result.put("code","300");
                    result.put("msg","操作失败！" + tomap.get("msg"));
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logInfo("重新出款异常:" + e);
        }
        return null;
    }


    /**
     * 商户出款请求参数
     * @Param []
     * @Return java.lang.String
     */
    public static Map<String,String> merPay(String ip,Integer port,String settleSerial) throws Exception{
        Map<String, String> payMap = new HashMap<String, String>();
        //平台失败重出
        payMap.put("settleSerial", settleSerial);	//流水号
        payMap.put("sourcetype", "3");	//数据来源  0 交易系统线下  1 交易系统线上 2 web平台T1出款  3 web平台失败重出
        payMap.put("pattern", "-1");	//默认 -1

        try{
            String data = JSONObject.toJSONString(payMap);
            LogUtils.logInfo("出款请求报文:" + settleSerial);
            LogUtils.logInfo("开始进行Socket连接:" + ip + " " + port);
            socket = new Socket(ip,port);   //115.182.230.164 7000    "10.71.11.12",25501
            LogUtils.logInfo("Socket连接成功:" + ip + " " + port);
            os = socket.getOutputStream();
            is = socket.getInputStream();
            byte[] by = data.getBytes("utf-8");
            String len = "0000"+by.length;
            len = len.substring(len.length()-4);
            byte[] lenlen = len.getBytes("utf-8");
            byte[] pack = new byte[4+by.length];
            System.arraycopy(lenlen, 0, pack, 0, 4);
            System.arraycopy(by, 0, pack, 4, by.length);
            System.out.println("请求包:"+asciiToString(pack));
            os.write(pack);
            os.flush();
            byte[] lenb=new byte[4];
            is.read(lenb, 0, 4);
            String str = asciiToString(lenb);
            str = str == null ? "" : str.trim();
            LogUtils.logInfo("结果:" + str);
           /* if (org.apache.commons.lang3.StringUtils.isBlank(str)) {
                throw new BusinessException("未获取到响应信息");
            }
            int rlen = Integer.parseInt(str);
            if(is.available() == rlen){
                byte[] be = new byte[4+rlen];
                System.arraycopy(lenb, 0, pack, 0, 4);
                is.read(be, 4, rlen);
                return JSONObject.parseObject(asciiToString(be),Map.class);
            }*/

        }catch (Exception e){
            LogUtils.logInfo("Socket连接失败/异常:" + e.getMessage());
            e.printStackTrace();
            LogUtils.logError("请求错误,请稍后重试",e);
        }finally {
            is.close();
            os.close(); //关闭Socket输出流
            socket.close();
        }
        return new HashMap<>();
    }

    public static String asciiToString(byte[] value) throws Exception {
        return new String(value, "utf-8");
    }

    /**
     *
     ********************************************************* .<br>
     * [方法] leftZero <br>
     * [描述] 左补零 <br>
     * [参数] 需补零的数据，是否变长 <br>
     * [返回] String <br>
     * [时间] 2015-12-7 下午5:51:05 <br>
     ********************************************************* .<br>
     */
    public static String leftZero(String s, int i) throws Exception {
        s = DateUtil.appendField("000", s);
        return s.substring(s.length() - i, s.length());
    }

    /**
     * 商户提现出款
     * @Param [data]
     * @Return void
     */
    public static String socket_TX(String ip,Integer port, String data) throws Exception {
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        String respStr = "";
        try {
            socket = new Socket(ip, port);
            os = socket.getOutputStream();
            is = socket.getInputStream();
            byte[] by = data.getBytes("UTF-8");
            byte[] lenlen = leftZero(by.length + "", 4).getBytes();
            byte[] pack = new byte[4 + by.length];
            pack = new LoFunction().assemble(lenlen, by);
            os.write(pack);
            os.flush();
            byte[] lenb = new byte[4];
            is.read(lenb, 0, 4);
            int rlen = Integer.parseInt(asciiToString(lenb));
            byte[] be = new byte[4 + rlen];
            System.arraycopy(lenb, 0, pack, 0, 4);
            is.read(be, 4, rlen);
            respStr = asciiToString(be);
            return respStr;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
            }
        }
        return "";
    }



    public static void main(String[] args) {
        String serial = "XYF20200804125930000000009239930";
        Map<String, String> s = newOut(serial);
        System.out.println(s);
    }

}
